package com.unlcn.ils.wms.web.controller.outbound;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.bo.outboundBO.BarCodeBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.OutboundTaskConfirmFormBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.WmsOutboundRecordListBO;
import com.unlcn.ils.wms.backend.bo.outboundBO.WmsOutboundTaskFormBO;
import com.unlcn.ils.wms.backend.service.outbound.OutBoundTaskService;
import com.unlcn.ils.wms.base.dto.WmsOutboundImportExcelDTO;
import com.unlcn.ils.wms.web.vo.outbound.OutboundTaskConfirmFormVO;
import com.unlcn.ils.wms.web.vo.outbound.WmsOutboundRecordListVO;
import com.unlcn.ils.wms.web.vo.outbound.WmsOutboundTaskFormVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 出库业务-表现层
 */

@Controller
@ResponseBody
@RequestMapping("/outboundTask")
public class OutboundTaskController {

    private Logger logger = LoggerFactory.getLogger(OutboundTaskController.class);

    @Autowired
    private OutBoundTaskService outBoundTaskService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    /**
     * 查询出库任务(备料任务)
     */
    @RequestMapping(value = "/getOutboundTaskList", method = RequestMethod.POST)
    public ResultDTO<Object> getOutboundTaskList(@RequestBody WmsOutboundTaskFormVO wmsOutboundTaskFormVO,
                                                 HttpServletRequest request) {
        logger.info("OutboundTaskController.getOutboundTaskList wmsOutboundTaskVO: {}", wmsOutboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");

        try {
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            taskFormBO.setOtWhCode(whCode);
            resultDTO.setData(outBoundTaskService.getOutboundTaskListForPage(taskFormBO));
        } catch (Exception e) {
            logger.error("OutboundTaskController.getOutboundTaskList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 交接单打印列表
     */
    @RequestMapping(value = "/getPrintOutboundTaskList", method = RequestMethod.POST)
    public ResultDTO<Object> getPrintOutboundTaskList(@RequestBody WmsOutboundTaskFormVO wmsOutboundTaskFormVO,
                                                      HttpServletRequest request) {
        logger.info("OutboundTaskController.getOutboundTaskList wmsOutboundTaskVO: {}", wmsOutboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");

        try {
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            taskFormBO.setOtWhCode(whCode);
            resultDTO.setData(outBoundTaskService.getPrintOutboundTaskList(taskFormBO));
        } catch (Exception e) {
            logger.error("OutboundTaskController.getOutboundTaskList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    @RequestMapping(value = "/updatePrintInfo/{otId}/{userId}", method = RequestMethod.POST)
    public ResultDTO<Object> updatePrintInfo(@PathVariable Long otId, @PathVariable Integer userId) {
        logger.info("OutboundTaskController.updatePrintInfo otId: {}{}", otId, userId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "成功更新打印信息");
        try {
            outBoundTaskService.updatePrintInfo(otId, userId);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.updatePrintInfo businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.updatePrintInfo error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 根据车架号查询备料信息
     */
    @RequestMapping(value = "/getPreparateInfoByVin/{vin}", method = RequestMethod.GET)
    public ResultDTO<Object> getPreparateInfoByVin(@PathVariable String vin) {
        WmsOutboundTaskFormVO wmsOutboundTaskFormVO = new WmsOutboundTaskFormVO();
        wmsOutboundTaskFormVO.setOtVin(vin);
        logger.info("OutboundTaskController.getPreparateInfoByVin param: {}", wmsOutboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            resultDTO.setData(outBoundTaskService.getPreparateInfoByVin(taskFormBO));
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.getPreparateInfoByVin businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.getPreparateInfoByVin error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 根据备料单号查询备料信息
     */
    @RequestMapping(value = "/getPreparateInfoByMaterialNo/{materialNo}", method = RequestMethod.GET)
    public ResultDTO<Object> getPreparateInfoByMaterialNo(@PathVariable String materialNo, HttpServletRequest request) {
        WmsOutboundTaskFormVO wmsOutboundTaskFormVO = new WmsOutboundTaskFormVO();
        wmsOutboundTaskFormVO.setOtPreparationMaterialNo(materialNo);
        logger.info("OutboundTaskController.getPreparateInfoByMaterialNo param: {}", wmsOutboundTaskFormVO);

        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录用户未绑定车库");
                return resultDTO;
            }
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            resultDTO.setData(outBoundTaskService.getPreparateInfoByMaterialNo(taskFormBO));
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.getPreparateInfoByMaterialNo businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.getPreparateInfoByMaterialNo error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 备料出库确认
     */
    @RequestMapping(value = "/updateTaskToOutbound", method = RequestMethod.POST)
    public ResultDTO<Object> updateTaskToOutbound(@RequestBody WmsOutboundTaskFormVO wmsOutboundTaskFormVO,
                                                  HttpServletRequest request) {
        logger.info("OutboundTaskController.updateTaskToOutbound param: {}", wmsOutboundTaskFormVO);

        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "备料出库确认成功");
        try {
            String userId = request.getHeader("userId");
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            if (StringUtils.isNotBlank(userId)) {
                taskFormBO.setUserId(userId);
            }
            outBoundTaskService.updateTaskToOutbound(taskFormBO);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.updateTaskToOutbound businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.updateTaskToOutbound error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("备料出库确认失败");
        }
        return resultDTO;
    }

    /**
     * 备料完成确认
     */
    @RequestMapping(value = "/updateTaskToConfirm", method = RequestMethod.POST)
    public ResultDTO<Object> updateTaskToConfirm(@RequestBody WmsOutboundTaskFormVO wmsOutboundTaskFormVO) {
        logger.info("OutboundTaskController.updateTaskToConfirm param: {}", wmsOutboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "备料完成确认成功");
        try {
            WmsOutboundTaskFormBO taskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(wmsOutboundTaskFormVO, taskFormBO);
            outBoundTaskService.updateTaskToConfirm(taskFormBO);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.updateTaskToConfirm businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.updateTaskToConfirm error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("备料完成确认失败");
        }
        return resultDTO;
    }

    /**
     * 出库记录查询
     * <p>
     * 2018-1-22 出库记录查询页面增加“物料代码”、“配置”、“颜色代码”、“颜色”字段显示(君马)，导出的文件中也需要包含这四个字段
     * 2018-3-16 出库记录查询页面条件查询增加物料名称字段
     * 2018-5-17 出库记录增加物流商,便于统计物流商承运数
     * 2018-6-12 出库记录增加经销商
     * </p>
     *
     * @param listVO 参数封装
     * @return 返回值
     * @version 1.0.32
     */
    @RequestMapping(value = "/getOutboundRecordList", method = RequestMethod.POST)
    public ResultDTO<Object> getOutboundRecordList(@RequestBody WmsOutboundRecordListVO listVO,
                                                   HttpServletRequest request) {
        logger.info("OutboundTaskController.getOutboundRecordList wmsOutboundTaskVO: {}", listVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            WmsOutboundRecordListBO taskFormBO = new WmsOutboundRecordListBO();
            BeanUtils.copyProperties(listVO, taskFormBO);
            String whCode = request.getHeader("whCode");
            taskFormBO.setOtWhCode(whCode);
            resultDTO.setData(outBoundTaskService.getOutboundRecordList(taskFormBO));
        } catch (BusinessException be) {
            logger.error("OutboundTaskController.getOutboundRecordList BusinessException: {}", be);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(be.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.getOutboundRecordList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 出库记录导出-君马和重庆
     * <p>
     * 2018-1-22 出库记录查询页面增加“物料代码”、“配置”、“颜色代码”、“颜色”字段显示(君马)，导出的文件中也需要包含这四个字段
     * </p>
     *
     * @param dto 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/outboundRecordImportExcel", method = RequestMethod.GET)
    public ResultDTO<Object> getOutboundRecordList(WmsOutboundImportExcelDTO dto,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response) {
        logger.info("OutboundTaskController.outboundRecordImportExcel param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            outBoundTaskService.updateOutboundImportExcel(dto, request, response);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.outboundRecordImportExcel BusinessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("OutboundTaskController.outboundRecordImportExcel error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }


    /**
     * 出库记录导出-(已重写)重写出库记录导出 新方法:getOutboundRecordList
     * <p>
     * 2018-1-22 出库记录查询页面增加“物料代码”、“配置”、“颜色代码”、“颜色”字段显示(君马)，导出的文件中也需要包含这四个字段
     * </p>
     *
     * @param dto 参数封装
     * @return 返回值
     */
    @Deprecated
    @RequestMapping(value = "/outboundRecordImportExcelOld", method = RequestMethod.GET)
    public ResultDTO<Object> getOutboundRecordListOld(WmsOutboundImportExcelDTO dto,
                                                      HttpServletRequest request,
                                                      HttpServletResponse response) {
        logger.info("OutboundTaskController.outboundRecordImportExcel param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        if (Objects.equals(dto, null)) {
            throw new BusinessException("参数为空!");
        }
        try {
            if (StringUtils.isBlank(dto.getWhCode())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录账户为绑定对应仓库");
                return resultDTO;
            }
            if (StringUtils.isBlank(dto.getUserId())) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("未登录");
                return resultDTO;
            }
            outBoundTaskService.updateOutboundImportExcelOld(dto, request, response);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.outboundRecordImportExcel error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("OutboundTaskController.outboundRecordImportExcel error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }


    /**
     * 出库记录条数
     */
    @RequestMapping(value = "/queryOutboundRecordCount", method = RequestMethod.GET)
    public ResultDTO<Object> queryOutboundRecordCount(WmsOutboundImportExcelDTO dto) {
        logger.info("OutboundTaskController.queryOutboundRecordCount param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        if (Objects.equals(dto, null)) {
            throw new BusinessException("参数为空!");
        }
        try {
            Integer integer = outBoundTaskService.countOutboundRecord(dto);
            if (integer == null || integer <= 0) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("没有对应的数据");
                return resultDTO;
            }
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.queryOutboundRecordCount error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception ex) {
            logger.error("OutboundTaskController.queryOutboundRecordCount error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 获取交接单打印信息
     *
     * @return 返回resultDto
     */
    @RequestMapping(value = "/getPrintInfo/{otId}", method = RequestMethod.GET)
    public ResultDTO<Object> getPrintInfo(@PathVariable Long otId) {
        logger.info("OutboundTaskController.getPrintInfo otId: {}", otId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取交接单数据成功");
        try {

            resultDTO.setData(outBoundTaskService.getPrintInfo(otId));
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.getPrintInfo businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("OutboundTaskController.getPrintInfo error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取交接单数据失败");
        }
        return resultDTO;
    }

    /**
     * 根据单据号获取车架号列表 - 君马库
     */
    @RequestMapping(value = "/getVinList/{barCode}", method = RequestMethod.GET)
    public ResultDTO<Object> getVinList(@PathVariable String barCode) {
        logger.info("OutboundTaskController.getVinList barCode: {}", barCode);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取数据成功");
        try {
            if (StringUtils.isBlank(barCode) || barCode.length() < 2) {
                resultDTO.setMessage("单据号有误, 请核实!");
                resultDTO.setSuccess(false);
                return resultDTO;
            }
            BarCodeBO barCodeBO = new BarCodeBO();
            //BeanUtils.copyProperties(barCodeVO, barCodeBO);
            if (StringUtils.isNotBlank(barCode)) {
                //String[] split = barCode.split("-");
                //if (split != null && split.length == 2){
                //    barCodeBO.setOrderNo(split[0]);
                //    barCodeBO.setType(split[1]);
                //}
                String orderType = barCode.substring(0, 2);
                if (StringUtils.isNotBlank(orderType)) {
                    barCodeBO.setOrderNo(barCode);
                    barCodeBO.setType(orderType);
                }
            }
            List<String> vinList = outBoundTaskService.getVinList(barCodeBO);
            if (CollectionUtils.isNotEmpty(vinList)) {
                resultDTO.setData(vinList);
            } else {
                //设置
                resultDTO.setMessage("单据号有误, 请核实!");
                resultDTO.setSuccess(false);
            }
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.getVinList businessException: {}", e);
            resultDTO.setMessage(e.getMessage());
            resultDTO.setSuccess(false);
        } catch (Exception e) {
            logger.error("OutboundTaskController.getVinList error: {}", e);
            resultDTO.setMessage("获取数据失败");
        }
        return resultDTO;
    }

    /**
     * 任务取消 - 重庆库
     */
    @RequestMapping(value = "/cancleTaskForCq", method = RequestMethod.POST)
    public ResultDTO<Object> cancleTaskForCq(@RequestBody WmsOutboundTaskFormVO outboundTaskFormVO) {
        logger.info("OutboundTaskController.cancleTaskForCq outboundTaskFormVO: {}", outboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "任务取消成功");
        try {
            WmsOutboundTaskFormBO outboundTaskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(outboundTaskFormVO, outboundTaskFormBO);
            outBoundTaskService.updateTaskToCancleForCq(outboundTaskFormBO);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.cancleTaskForCq businessException: {}", e);
            resultDTO.setMessage(e.getMessage());
            resultDTO.setSuccess(false);
        } catch (Exception e) {
            logger.error("OutboundTaskController.cancleTaskForCq error: {}", e);
            resultDTO.setMessage("任务取消失败");
            resultDTO.setSuccess(false);
        }
        return resultDTO;
    }

    /**
     * <p>
     * 页面的出库确认功能调整到app进行
     * </p>
     * 出库确认 - 君马库
     */
    @RequestMapping(value = "/outConfirmOld", method = RequestMethod.POST)
    public ResultDTO<Object> outConfirmOld(@RequestBody OutboundTaskConfirmFormVO taskConfirmFormVO, HttpServletRequest request) {
        logger.info("OutboundTaskController.outConfirmOld taskConfirmFormVO: {}", taskConfirmFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "出库确认成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                throw new BusinessException("当前用户未绑定仓库");
            }
            if (CollectionUtils.isEmpty(taskConfirmFormVO.getVinList())) {
                throw new BusinessException("暂没有可以出库的数据");
            }
            OutboundTaskConfirmFormBO taskConfirmFormBO = new OutboundTaskConfirmFormBO();
            BeanUtils.copyProperties(taskConfirmFormVO, taskConfirmFormBO);
            if (StringUtils.isNotBlank(taskConfirmFormVO.getBarCode())) {
                String[] split = taskConfirmFormVO.getBarCode().split("-");
                if (split.length == 2) {
                    taskConfirmFormBO.setOrderNo(split[0]);
                    taskConfirmFormBO.setType(split[1]);
                }
            }
            resultDTO.setData(outBoundTaskService.updateToOutConfirm(taskConfirmFormBO, whCode));
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.outConfirmOld businessException: {}", e);
            resultDTO.setMessage(e.getMessage());
            resultDTO.setSuccess(false);
        } catch (Exception e) {
            logger.error("OutboundTaskController.outConfirmOld error: {}", e);
            resultDTO.setMessage("出库确认失败");
        }
        return resultDTO;
    }


    /**
     * 备料退库
     */
    @RequestMapping(value = "/quitTaskForCq", method = RequestMethod.POST)
    public ResultDTO<Object> quitTaskForCq(@RequestBody WmsOutboundTaskFormVO outboundTaskFormVO, HttpServletRequest request) {
        logger.info("OutboundTaskController.quitTaskForCq outboundTaskFormVO: {}", outboundTaskFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "备料退库成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setMessage("当前登录用户未绑定仓库");
                resultDTO.setSuccess(false);
                return resultDTO;
            }
            WmsOutboundTaskFormBO outboundTaskFormBO = new WmsOutboundTaskFormBO();
            BeanUtils.copyProperties(outboundTaskFormVO, outboundTaskFormBO);
            outboundTaskFormBO.setOtWhCode(whCode);
            outBoundTaskService.updateTaskToQuitForCq(outboundTaskFormBO);
        } catch (BusinessException e) {
            logger.error("OutboundTaskController.quitTaskForCq businessException: {}", e);
            resultDTO.setMessage(e.getMessage());
            resultDTO.setSuccess(false);
        } catch (Exception e) {
            logger.error("OutboundTaskController.quitTaskForCq error: {}", e);
            resultDTO.setMessage("任务取消失败");
            resultDTO.setSuccess(false);
        }
        return resultDTO;
    }
}
